package com.hengyue.security.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hengyue.common.constants.HttpStatus;
import com.hengyue.common.core.result.AjaxResult;
import com.hengyue.common.core.result.ResultCode;
import com.hengyue.common.utils.ResponseUtils;
import com.hengyue.common.utils.ServletUtils;
import com.hengyue.common.utils.StringUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serializable;

/**
 * 认证异常处理
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
            throws IOException, ServletException {
        int code = HttpStatus.UNAUTHORIZED;
        String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        ServletUtils.renderString(response, objectMapper.writeValueAsString(AjaxResult.error(code, msg)));
    }
}
